import singleton from "@/util/singleton.js"

import {
	userStore,
	chatStore
} from "@/store/index.js"
import tools from "./tools";

const user = userStore();
const chat = chatStore();

const url = "ws://ai.qinhai269.com:7272"
// const url = "ws://0.0.0.0:7272"
class Push {
	constructor() {
		//主动退出
		this.me_close = false;
		this.socketTask;
		this.deviceId = "";
		this.status = false;

		// 监听连接关闭close
		uni.onSocketClose((e) => {
			this.socketTask = null;
			console.log('监听连接关闭');
			if (!this.me_close) { //判断是否主动关闭进行重新连接
				setTimeout(_ => {
					this.#connect()
				}, 5000)
			}
		})

		uni.onSocketError((err) => {
			console.log('连接失败，请检查');
			this.socketTask = null;
			if (!this.me_close) { //判断是否主动关闭进行重新连接
				setTimeout(_ => {
					this.#connect()
				}, 2000)
			}
		})

		uni.onSocketOpen((res) => {
			// console.log('连接成功！');
			this.status = true;
		});

		uni.onSocketMessage(function(res) {
			let data = JSON.parse(res.data)
			if (data.type != "ping") {
				// console.log('接受数据', data)
				setTimeout(_ => {
					chat.add(data)
					uni.$emit('message', data);
				}, 800)
				
				if (data.status == 402) {
					this.me_close = true;
					uni.showModal({
						title: "退出提示",
						content: data.msg,
						success(res) {
							user.logout()
							chat.clear()
							if (res.confirm) {
								uni.navigateTo({
									url: "/pages/user/login/login"
								})
							}
						}
					})
				}
			}
		});
	}

	start() {
		this.#connect()
	}

	#connect() {
		this.socketTask = uni.connectSocket({
			url: `${url}?token=${user.token}`
		});
	}

	reconnect() {
		this.close();
		this.socketTask = null;
		this.#connect();
	}

	close() {
		this.me_close = true
		uni.closeSocket({
			success() {
				// 确保已经关闭
				this.socketTask = null;
				this.me_close = true;
				console.log('关闭连接')
			}
		})
	}

	send(content, type = 'me') {
		let _this = this;
		let data = {
			token: user.token,
			type,
			content
		}
		uni.sendSocketMessage({
			data: JSON.stringify(data),
			success() {
				delete data.token
				data.created_at = tools.formatDate(Date.now(), 'Y/M/D h:m')
				chat.add(data)
			},
			fail(err) {
				console.log("失败", err);
			},
		});
	}

	watch(callback) {
		uni.onSocketMessage(function(res) {
			let data = JSON.parse(res.data)
			if (data.type != "ping") {
				if (typeof callback === 'function') {
					callback(data)
				}
			}
		});
	}
}
export default singleton(Push)